package com.itboye.mengwu.app.ui.aiwujia;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ImageCompressAndUpload;
import com.itboye.core.utils.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.SoftwareUtil;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.data.model.BiaoQianModel;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.presenter.BiaoQianPresenter;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.publish.photo.util.Bimp;
import com.itboye.mengwu.testpic.ui.FileUtils;
import com.itboye.mengwu.testpic.ui.PhotoActivity;
import com.itboye.mengwu.ui.shop.FlowLayout;
import com.itboye.mengwu.widget.MyGridView;
import com.itboye.mengwu.widget.PhotoSelectFragment;
import com.itboye.mengwu.widget.PhotoSelectFragment.PhotoSelectListener;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class ActivityAiwujiaYuErjingPublish extends BaseActivity implements
		Observer, OnClickListener {

	public final int EXTERNAL_CAMERA_REQ_CODE = 11;
	public final int EXTERNAL_STORE_REQ_CODE = 12;
	PopupWindows popupWindows;
	private MyGridView aiWuJiaGridView;
	private GridAdapter adapter;
	// private TextView activity_selectimg_send;
	// private ImageView imgPublishBack;
	// 标题
	private EditText edttitle;
	// 内容
	private EditText edtcontext;
	private String title;
	private String contextEd;
	TextView txt_save;
	TieZiPresenter tanPresenter;
	public final static int HU = 1;
	TextView ask, share;
	RelativeLayout publish;
	ArrayList<TextView> childView;
	ArrayList<TextView> addbq = new ArrayList<TextView>();
	FlowLayout tianjiabiaoqian;
	TextView tv;
	int posion = 0;
	boolean isshow = false;
	ImageView add_baioqian;
	public static ArrayList<String> imgUrls = new ArrayList<String>();
	ImageView back;
	TextView txt_title;
	// Button btn_ok;
	TextView txt_cancel;
	FlowLayout flowLayout;
	LinearLayout bianji;
	BiaoQianPresenter biaoqianPresenter;
	BiaoQianModel biaoQianModel;
	ArrayList<BiaoQianModel> arrayList = new ArrayList<BiaoQianModel>();
	StringBuilder stringBuilder = new StringBuilder();
	StringBuilder builder = new StringBuilder();
	EditText edittext;
	TextView sure;
	int count;
	View view3 = null;
	LinkedList<View> linkedList = new LinkedList<>();
	private LinearLayout.LayoutParams params;
	// 存放标签和标签选择状态
	final List<TextView> tagView = new ArrayList<>();
	final List<Boolean> tagViewState = new ArrayList<>();
	ArrayList<String> arrayTags = new ArrayList<String>();
	ImageView img, img2;
	protected Bitmap bitmap;
	int screenWidth, screenHeight;
	ScrollView sc;

	public void setImageViewMathParent(Bitmap bitmap, ImageView image) {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		float scalew = (float) displayMetrics.widthPixels
				/ (float) bitmap.getWidth();
		image.setScaleType(ScaleType.MATRIX);
		Matrix matrix = new Matrix();
		image.setAdjustViewBounds(true);
		if (displayMetrics.widthPixels < bitmap.getWidth()) {
			matrix.postScale(scalew, scalew);
		} else {
			matrix.postScale(1 / scalew, 1 / scalew);
		}
		image.setMaxWidth(displayMetrics.widthPixels);
		float ss = displayMetrics.heightPixels > bitmap.getHeight() ? displayMetrics.heightPixels
				: bitmap.getHeight();
		image.setMaxWidth((int) ss);
		image.setImageBitmap(bitmap);
		if (bitmap != null && bitmap.isRecycled()) {
			bitmap.recycle();
		}

	}

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_publish;
	}

	/**
	 * 创建一个正常状态的标签
	 * 
	 * @param tag
	 * @return
	 */
	private TextView getTag(String tag) {
		TextView textView = new TextView(getApplicationContext());
		textView.setTextSize(12);
		textView.setBackgroundResource(R.drawable.tag_normal);
		textView.setTextColor(R.color.black);
		textView.setText(tag);
		textView.setLayoutParams(params);
		return textView;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onMyCreate() {
		// Bitmap
		// bitmap=ImageLoader.getInstance().loadImageSync("http://material.mediav.com/galileo/20160415/bbf7318efb4daaed716e2b80cf83f77e.jpg");
		// img.setImageBitmap(bitmap);
		//
		// new Thread(runnable).start();

		// android.widget.RelativeLayout.LayoutParams
		// layoutParams=(android.widget.RelativeLayout.LayoutParams) new
		// LayoutParams(getWindowManager().getDefaultDisplay().getWidth(),getWindowManager().getDefaultDisplay().getWidth());
		// img.setLayoutParams(layoutParams);
		// Picasso.with(this)
		// .load("http://material.mediav.com/galileo/20160415/bbf7318efb4daaed716e2b80cf83f77e.jpg")
		// .transform(transformation)
		// .into(img);
		params = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		params.setMargins(10, 10, 0, 0);
		tanPresenter = new TieZiPresenter(this);
		tianjiabiaoqian = (FlowLayout) findViewById(R.id.tianjiabiaoqian);
		txt_title.setText("发布内容");
		txt_cancel.setText("发布");
		txt_cancel.setTextColor(getResources().getColor(R.color.white));
		Init();
		biaoqianPresenter = new BiaoQianPresenter(this);
		String uid = (String) SPUtils.get(this, null, SpPublicParams.UID, "");
		biaoqianPresenter.QueryBiaoQian(uid, "2", "10");
		edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
							.showSoftInput(edittext, 0);
				} else {
					bianji.setVisibility(View.GONE);
				}
			}
		});
		add_baioqian.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				bianji.setVisibility(View.VISIBLE);
				edttitle.setFocusableInTouchMode(false);
				edttitle.setFocusable(false);
				edtcontext.setFocusableInTouchMode(false);
				edtcontext.setFocusable(false);
				isshow = true;
				edittext.setFocusable(true);
				edittext.setFocusableInTouchMode(true);
				edittext.requestFocus();
				// sc.smoothScrollTo(xx, xy);
				sure.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						count++;
						String editTextContent = edittext.getText().toString();
						// 判断输入是否为空
						if (editTextContent.equals("")) {
							ByAlert.alert("不能为空哦");
							return;
						} else {

							// 判断标签是否重复添加
							if (count >= 7) {
								count = 6;
								ByAlert.alert("只能添加6个标签哦");
								bianji.setVisibility(View.GONE);
							} else {
								bianji.setVisibility(View.VISIBLE);
								for (TextView tag : tagView) {
									String tempStr = tag.getText().toString();
									if (tempStr.equals(editTextContent)) {
										ByAlert.alert("不允许重复添加");
										count--;
										return;
									}
									builder.append(editTextContent + ",");
								}
								addTags(editTextContent);
							}

						}
					}
				});

			}
		});

	}

	@SuppressWarnings("deprecation")
	public static Drawable resizeImage(Bitmap bitmap, int screenWidth) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int newWidth = screenWidth;
		int newHeight = screenWidth / width * height; // 根据屏幕的宽度，计算按比较缩放后的高度

		// calculate the scale
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// create a matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the Bitmap
		matrix.postScale(scaleWidth, scaleHeight);
		// if you want to rotate the Bitmap
		// matrix.postRotate(45);
		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		// make a Drawable from Bitmap to allow to set the Bitmap
		// to the ImageView, ImageButton or what ever
		return new BitmapDrawable(resizedBitmap);

	}

	public void addTags(String text) {
		if (count >= 6) {
			add_baioqian.setVisibility(View.GONE);
		} else {
			add_baioqian.setVisibility(View.VISIBLE);
		}
		// 添加标签
		final TextView temp = getTag(text);
		arrayTags.add(text);
		tagView.add(temp);
		tagViewState.add(false);
		// 添加点击事件，点击变成选中状态，选中状态下被点击则删除
		temp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				int curIndex = tagView.indexOf(temp);
				if (!tagViewState.get(curIndex)) {
					// 显示 ×号删除
					temp.setText(temp.getText() + " ×");
					temp.setBackgroundResource(R.drawable.tag_selected);
					temp.setTextColor(R.color.black);
					// 修改选中状态
					tagViewState.set(curIndex, true);

				} else {
					tianjiabiaoqian.removeView(temp);
					tagView.remove(curIndex);
					tagViewState.remove(curIndex);
					arrayTags.remove(curIndex);
					count--;
					if (count >= 6) {
						count = 6;
						add_baioqian.setVisibility(View.GONE);
					} else {
						add_baioqian.setVisibility(View.VISIBLE);
					}

				}
			}
		});
		System.out.println("temp" + temp + "tianjiabiaoqian" + tianjiabiaoqian);
		tianjiabiaoqian.addView(temp, tianjiabiaoqian.getChildCount() - 1);
		// 让编辑框在最后一个位置上
		// edittext.bringToFront();
		// 清空编辑框
		edittext.setText("");
		bianji.setVisibility(View.GONE);
		edittext.requestFocus();
	}

	private StringBuffer attachments;
	protected ArrayList<String> uploadedUrl = new ArrayList<String>();

	public void Init() {
		aiWuJiaGridView = (MyGridView) findViewById(R.id.aiWuJiaGridView);
		aiWuJiaGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		aiWuJiaGridView.setAdapter(adapter);
		aiWuJiaGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == imgUrls.size()) {
					SoftwareUtil.showOrHideSoftware(arg1,
							MainApplication.context, false);
					popupWindows = new PopupWindows(
							ActivityAiwujiaYuErjingPublish.this,
							aiWuJiaGridView);
				} else {
					Intent intent = new Intent(
							ActivityAiwujiaYuErjingPublish.this,
							PhotoActivity.class);
					intent.putExtra("imgUrls", imgUrls);
					intent.putExtra("ID", arg2);
					intent.putExtra("type", "yuerjing");
					startActivityForResult(intent, 101);// (intent);
					// finish();
					// adapter.notifyDataSetChanged();
				}
			}
		});

	}

	public void onBitMap() {

		List<String> list = new ArrayList<String>();
		for (int i = 0; i < imgUrls.size(); i++) {
			String Str = imgUrls.get(i).substring(
					imgUrls.get(i).lastIndexOf("/") + 1,
					imgUrls.get(i).lastIndexOf("."));
			list.add(FileUtils.SDPATH + Str + ".JPEG");
		}
		for (int i = 0; i < arrayTags.size(); i++) {
			stringBuilder.append(arrayTags.get(i) + ",");
		}

		// 高清的压缩图片全部就在 list 路径里面了
		// 高清的压缩过的 bmp 对象 都在 imgUrls里面
		// 完成上传服务器后 .........

		title = edttitle.getText().toString().trim();
		contextEd = edtcontext.getText().toString().trim();
		// if (title == null || title == "" || title.length() == 0) {
		// ByAlert.alert("请输入标题");
		// try {
		// closeProgressDialog();
		//
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
		// return;
		// }
		if (contextEd == null || contextEd == "") {
			ByAlert.alert("内容不能为空哦");
			try {
				closeProgressDialog();
			} catch (Exception e) {
				// TODO: handle exception
			}
			return;
		} else if (contextEd.length() < 5) {
			ByAlert.alert("内容不能少于五个字哦");
			try {
				closeProgressDialog();
			} catch (Exception e) {
				// TODO: handle exception
			}
			return;

		}
		showProgressDialog("发布中，请稍后", true);
		final TieZiPresenter tanPresenter = new TieZiPresenter(this);
		if (imgUrls.size() > 0) {
			for (int j = 0; j < imgUrls.size(); j++) {
				System.out.println("路径" + imgUrls.get(j));
				ImageCompressAndUpload.getInstance().execute(imgUrls.get(j),
						new OnUploadlistener() {

							@Override
							public void OnSuccess(String resultData) {
								uploadedUrl.add(resultData);
								System.out.println("rse" + resultData);
								if (uploadedUrl.size() == imgUrls.size()) {
									if (uploadedUrl.size() > 0) {

										attachments = new StringBuffer();
										attachments.append(uploadedUrl.get(0));
										for (int i = 1; i < uploadedUrl.size(); i++) {
											attachments.append(",").append(
													uploadedUrl.get(i));
										}

									}
									LuntanTieZiBean bean = new LuntanTieZiBean();
									bean.setUid((String) SPUtils
											.get(ActivityAiwujiaYuErjingPublish.this,
													null, SpPublicParams.UID,
													""));
									bean.setSubject(title);
									bean.setMessage(contextEd);
									bean.setAuthor((String) SPUtils
											.get(ActivityAiwujiaYuErjingPublish.this,
													null,
													SpPublicParams.NICK_NAME,
													""));
									bean.setFid(fid + "");
									bean.setAttachments(attachments);
									Log.e("hu  stringBuilder=",
											stringBuilder.toString());
									if (stringBuilder.length() != 0
											&& builder.length() != 0) {
										bean.setTags(""
												+ stringBuilder
												+ builder.substring(0,
														builder.length() - 1));
									} else if ((stringBuilder == null || stringBuilder
											.toString() == "")
											&& builder.length() != 0) {
										bean.setTags(""
												+ builder.substring(0,
														builder.length() - 1));
									} else if ((builder == null || builder
											.toString() == "")
											&& stringBuilder.length() != 0) {
										bean.setTags(""
												+ stringBuilder
														.substring(
																0,
																stringBuilder
																		.length() - 1));
									} else if (stringBuilder.length() == 0
											&& builder.length() == 0) {
										bean.setTags(null);
									}
									tanPresenter.add(bean);
									ByAlert.alert("发表成功");
									finish();
								}

							}

							@Override
							public void OnError(String resultData) {
								ByAlert.alert("发表出错了╰(￣▽￣)╭");
								// toast.show();
							}
						}, "bbs");
			}
		} else {
			LuntanTieZiBean bean = new LuntanTieZiBean();
			bean.setUid((String) SPUtils.get(
					ActivityAiwujiaYuErjingPublish.this, null,
					SpPublicParams.UID, ""));
			bean.setSubject(title);
			bean.setMessage(contextEd);
			bean.setAuthor((String) SPUtils.get(
					ActivityAiwujiaYuErjingPublish.this, null,
					SpPublicParams.NICK_NAME, ""));
			bean.setFid(fid + "");
			bean.setAttachments(null);
			Log.d("hu ==tag", "builder=" + builder.toString()
					+ ", stringbuilder=" + stringBuilder.toString()
					+ ",builder.len=" + builder.length());
			if (stringBuilder.length() != 0 && builder.length() != 0) {
				bean.setTags("" + stringBuilder
						+ builder.substring(0, builder.length() - 1));
			} else if ((stringBuilder == null || stringBuilder.toString() == "")
					&& builder.length() != 0) {
				bean.setTags("" + builder.substring(0, builder.length() - 1));
			} else if ((builder == null || builder.toString() == "")
					&& stringBuilder.length() != 0) {
				bean.setTags(""
						+ stringBuilder.substring(0, stringBuilder.length() - 1));
			} else if (stringBuilder.length() == 0 && builder.length() == 0) {
				bean.setTags(null);
			}
			tanPresenter.add(bean);
			ByAlert.alert("发表成功");
			finish();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private int selectedPosition = -1;
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			if (imgUrls.size() == 9) {
				return 9;
			}
			return (imgUrls.size() + 1);
		}

		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == imgUrls.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				if (imgUrls.size() > 0)
					XImageLoader.load("file://" + imgUrls.get(position),
							holder.image);
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.tempSelectBitmap.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							Bimp.max += 1;
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
						}
					}
				}
			}).start();
		}
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					cameraPermission();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					storePermission();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	class PhotoSelect implements PhotoSelectListener {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {
				// XImageLoader.load("file://" + string,
				// (ImageView) v.findViewById(R.id.img));
				imgUrls.add(string);

			}
			adapter = new GridAdapter(ActivityAiwujiaYuErjingPublish.this);
			aiWuJiaGridView.setAdapter(adapter);
			// adapter.notifyDataSetChanged();
		}

	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";
	public String addr;
	protected ImageView img_del;
	private View view2;
	protected View view;
	private String fid = "8";

	// Log.e("hu", "fid 1=" + fid);
	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/myimage/", String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
		// Bitmap bitmap = ImageLoader
		// .getInstance()
		// .loadImageSync(
		// "http://material.mediav.com/galileo/20160415/bbf7318efb4daaed716e2b80cf83f77e.jpg");
		// img.setImageBitmap(bitmap);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (imgUrls.size() < 9 && resultCode == -1) {
				imgUrls.add(path);
				adapter = new GridAdapter(this);
				aiWuJiaGridView.setAdapter(adapter);
			}
			break;
		}
		if (requestCode == 101 && resultCode == 102) {
			adapter = new GridAdapter(this);
			aiWuJiaGridView.setAdapter(adapter);
		}
	}

	@SuppressLint("InflateParams")
	@SuppressWarnings("deprecation")
	private void settagname() {

		// TODO Auto-generated method stub

		childView = new ArrayList<TextView>();

		for (int i = 0; i < arrayList.size(); i++) {
			posion = i;
			flowLayout = (FlowLayout) findViewById(R.id.flowLayout);
			view2 = LayoutInflater.from(this).inflate(R.layout.textview, null);

			TextView textView = (TextView) view2.findViewById(R.id.text);
			ImageView img_del = (ImageView) view2.findViewById(R.id.img_del);
			textView.setText(arrayList.get(i).getName());
			img_del.setVisibility(View.GONE);
			// Log.d("hu", arrayList.get(i).getName());
			textView.setGravity(Gravity.CENTER);
			textView.setTextColor(getResources().getColor(R.color.black));
			textView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.biaoqianshape2));
			textView.setTag(R.id.tag_second, i);
			textView.setTag(R.id.tag_fourth, arrayList.get(i).getName());
			textView.setTag(true);
			childView.add(textView);
			android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			lP.setMargins(10, 10, 10, 10);
			flowLayout.addView(view2, lP);
			textView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(final View vv) {
					// TODO Auto-generated method stub
					count++;
					if (count >= 7) {
						count = 6;
						ByAlert.alert("只能添加6个");
						add_baioqian.setVisibility(View.GONE);
					} else {
						add_baioqian.setVisibility(View.VISIBLE);
						// 判断标签是否重复添加
						for (TextView tag : tagView) {
							String tempStr = tag.getText().toString();
							if (tempStr.equals(vv.getTag(R.id.tag_fourth) + "")) {
								ByAlert.alert("不允许重复添加标签");
								count--;
								return;
							}
						}
						addTags(vv.getTag(R.id.tag_fourth) + "");
					}
				}

			});
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		imgUrls.clear();
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == TieZiPresenter.AddTieZiSuccess) {
				// ByAlert.alert(entity.getData() + "");
				edtcontext.setText("");
				edttitle.setText("");
				finish();
			} else if (entity.getEventType() == TieZiPresenter.AddTieZiFail) {
				ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == BiaoQianPresenter.queryBiaoQIan_success) {
				arrayList.addAll((ArrayList<BiaoQianModel>) entity.getData());
				settagname();
			} else if (entity.getEventType() == BiaoQianPresenter.queryBiaoQIan_success) {
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		// case R.id.publish:
		// edttitle.setFocusable(true);
		// edttitle.setFocusableInTouchMode(true);
		// edtcontext.setFocusable(true);
		// edtcontext.setFocusableInTouchMode(true);
		// break;
		case R.id.back:
			imgUrls.clear();
			finish();
			break;
		case R.id.edttitle:
			edttitle.setFocusable(true);
			edttitle.setFocusableInTouchMode(true);
			edtcontext.setFocusable(true);
			edtcontext.setFocusableInTouchMode(true);
			break;
		case R.id.edtcontext:
			edttitle.setFocusable(true);
			edttitle.setFocusableInTouchMode(true);
			edtcontext.setFocusable(true);
			edtcontext.setFocusableInTouchMode(true);
			break;
		case R.id.txt_cancel:
			onBitMap();
			break;
		case R.id.ask:
			ask.setTextColor(getResources().getColor(R.color.main_color));
			ask.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.btn2));
			share.setTextColor(getResources().getColor(R.color.black_view));
			share.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.btn1));
			fid = "8";
			break;
		case R.id.share:
			share.setTextColor(getResources().getColor(R.color.main_color));
			share.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.btn2));
			ask.setTextColor(getResources().getColor(R.color.black_view));
			ask.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.btn1));
			fid = "7";
			break;

		default:
			break;
		}
	}

	public void cameraPermission() {
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.CAMERA)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则打不开相机。",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行权限请求
				ActivityCompat.requestPermissions(this,
						new String[] { Manifest.permission.CAMERA },
						EXTERNAL_CAMERA_REQ_CODE);
			}
		} else {
			photo();
			popupWindows.dismiss();
		}
	}

	public void storePermission() {
		if (ContextCompat.checkSelfPermission(this,
				Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则不能读取相册。",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行权限请求
				ActivityCompat.requestPermissions(this, new String[] {
						Manifest.permission.WRITE_EXTERNAL_STORAGE,
						Manifest.permission.READ_EXTERNAL_STORAGE },
						EXTERNAL_STORE_REQ_CODE);
			}
		} else {

			new PhotoSelectFragment(new PhotoSelect(), 9).show(
					getSupportFragmentManager(), null);
			popupWindows.dismiss();
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] arg1,
			int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, arg1, grantResults);

		switch (requestCode) {

		case EXTERNAL_CAMERA_REQ_CODE: {
			if (grantResults == null || "".equals(grantResults)) {
				return;
			} else {
				if (grantResults.length > 0
						&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					// 申请成功，进行相应操作
					photo();
					popupWindows.dismiss();
				} else {
					// 申请失败，可以继续向用户解释。

				}
			}
			return;
		}
		case EXTERNAL_STORE_REQ_CODE: {

			if (grantResults.length > 0
					&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				// 申请成功，进行相应

				PhotoSelectFragment photoSelectFragment = new PhotoSelectFragment(
						new PhotoSelect(), 9);
				photoSelectFragment.show(getSupportFragmentManager(), null);
				popupWindows.dismiss();
			} else {
				// 申请失败，可以继续向用户解释。

			}
			return;
		}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle arg0) {
		// TODO Auto-generated method stub
		// super.onSaveInstanceState(arg0);
	}
}
